import React, { useMemo } from "react";
import { getLastLetter, getNameAbbreviation } from "../../utils/stringUtil";
import "./style.less";

export interface UserAvatarProps {
  /**
   * 用户名，用于生成头像内容
   */
  name: string;
  /**
   * 头像尺寸
   */
  size?: number | "small" | "default" | "large";
  /**
   * 头像形状
   */
  shape?: "circle" | "square";
  /**
   * 背景颜色，可以是预设颜色数组或自定义颜色
   */
  colors?: string[] | string;
  /**
   * 文字颜色
   */
  textColor?: string;
  /**
   * 是否使用用户名缩写（取首字母）而不是最后一个字符
   */
  useAbbreviation?: boolean;
  /**
   * 自定义样式类名
   */
  className?: string;
  /**
   * 自定义样式
   */
  style?: React.CSSProperties;

  /**
   * 自定义头像
   */
  avatar?: string;
  /**
   * 点击事件
   */
  onClick?: React.MouseEventHandler<HTMLDivElement>;
}

// 预设的背景颜色
const DEFAULT_COLORS = [
  "#28BBA9", //
  "#2DD4C0", //
  "#8A5BF2", //
  "#4551E5", //
  "#FBB910", //
];

// 尺寸映射
const SIZE_MAP = {
  small: 20,
  default: 28,
  large: 56,
};

/**
 * 用户头像组件
 *
 * 根据用户名生成头像，显示用户名的最后一个字符或缩写
 */
const UserAvatar: React.FC<UserAvatarProps> = ({
  name,
  size = "default",
  shape = "circle",
  colors = DEFAULT_COLORS,
  textColor = "#ffffff",
  useAbbreviation = false,
  className = "",
  style,
  onClick,
  avatar,
}) => {
  // 计算头像尺寸
  const avatarSize = useMemo(() => {
    if (typeof size === "number") {
      return size;
    }
    return SIZE_MAP[size] || SIZE_MAP.default;
  }, [size]);

  // 根据 avatar 确定背景颜色
  const backgroundColor = useMemo(() => {
    if (typeof avatar === "string" && ["1", "2", "3", "4"].includes(avatar)) {
      const index = parseInt(avatar, 10) - 1;
      return DEFAULT_COLORS[index] || DEFAULT_COLORS[0];
    }

    if (typeof colors === "string") {
      return colors;
    }

    if (Array.isArray(colors) && colors.length > 0) {
      const hashCode = name.split("").reduce((acc, char) => {
        return acc + char.charCodeAt(0);
      }, 0);

      const colorIndex = hashCode % colors.length;
      return colors[colorIndex];
    }

    return DEFAULT_COLORS[0];
  }, [name, colors, avatar]);

  // 计算显示的字符
  const displayChar = useMemo(() => {
    if (!name) return "?";

    if (useAbbreviation) {
      return getNameAbbreviation(name, 1);
    }

    return getLastLetter(name);
  }, [name, useAbbreviation]);

  // 计算文字大小 - 根据头像尺寸自动调整
  const fontSize = Math.max(Math.floor(avatarSize / 2), 12);

  return (
    <div
      className={`user-avatar user-avatar-${shape} ${className}`}
      style={{
        width: avatarSize,
        height: avatarSize,
        backgroundColor,
        fontSize: `${fontSize}px`,
        color: textColor,
        ...style,
      }}
      onClick={onClick}
    >
      {avatar &&
      typeof avatar === "string" &&
      !["1", "2", "3", "4"].includes(avatar) ? (
        <img
          src={avatar}
          alt="avatar"
          style={{
            width: "100%",
            height: "100%",
            borderRadius: shape === "circle" ? "50%" : "0",
          }}
        />
      ) : (
        displayChar.toUpperCase()
      )}
    </div>
  );
};

export default UserAvatar;
